/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.npmpackage.core.npmsetting;

import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.npmpackage.api.entity.settings.NpmSettings;

import java.util.Arrays;

/**
 * npm 配置参数读取
 *
 * @author noah
 */
class NpmSettingReader {
    /**
     * 读取server下对应的npm配置参数
     *
     * @param nodeJsPath nodejs路径
     * @return
     */
    public static NpmSettings read(String nodeJsPath) {
        String npmSettingFilePath = NpmSettingPathManager.getNpmSettingFilePath(nodeJsPath);
        // 如果文件不存在 那么无需进行解析
        if (!NpmSettingPathManager.exists(npmSettingFilePath)) {
            WebLogger.Instance.info("npm settings config file not exists, jit-engine will create with default content! the path is " + npmSettingFilePath, NpmSettingReader.class.getName());
            return null;
        }

        String strNpmSettings = FileUtility.readAsString(npmSettingFilePath);

        try {
            // 如果转换失败  即读取到的文件内容无法转换成npm配置参数信息
            return SerializeUtility.getInstance().deserialize(strNpmSettings, NpmSettings.class);
        } catch (Exception e) {
            WebLogger.Instance.info("read npmsettings failed,please check! the path is :" + npmSettingFilePath + "  , and the reason is " + Arrays.toString(e.getStackTrace()), NpmSettingReader.class.getName());
        }
        return null;
    }
}
